<template>
  <div>
    <!-- 标题 -->
    <TaiTitle :title="title">
      <el-dropdown trigger="click" placement="bottom-start" @command="floorCommand">
        <el-icon class="ml20" style="cursor: pointer;"><MoreFilled /></el-icon>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item command="add">添加房间</el-dropdown-item>
            <el-dropdown-item command="delFloor">删除整层</el-dropdown-item>
            <el-dropdown-item command="batchLock">批量关联公区锁</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </TaiTitle>
    <div class="floor-flexrow">
      <div class="floor-flexrow-wrap">
        <el-dropdown trigger="click" placement="right" v-for="item in roomList" :key="item" @command="roomCommand($event, item)">
          <el-card shadow="hover" class="room-item" :class="{ 'is-checked-in': item.checkInInfo && Object.keys(item.checkInInfo).length !== 0 }">
            <div class="room-content">
              <div class="room-header">
                <span class="room-name">{{ item.roomName }}</span>
              </div>

              <div class="room-footer">
                <div class="room-icons">
                  <template v-if="hasDevices(item)">
                    <div class="icon-item" v-if="(item.associatedLockList && item.associatedLockList.length !== 0) || (item.associatedFaceLockList && item.associatedFaceLockList.length !== 0)">
                      <el-icon><Lock /></el-icon>
                    </div>
                    <div class="icon-item" v-if="item.associatedMeterList && item.associatedMeterList.length !== 0">
                      <el-icon><Odometer /></el-icon>
                    </div>
                    <div class="icon-item" v-if="item.roomDirtyStatus === '1'">
                      <el-tooltip content="脏房" placement="top">
                        <el-icon class="dirty-icon"><Brush /></el-icon>
                      </el-tooltip>
                    </div>
                  </template>
                </div>

                <div class="room-status">
                  <span v-if="item.checkInInfo && Object.keys(item.checkInInfo).length !== 0"
                        :class="{ 'is-expired': item.checkInInfo.betweenNowDays < 0 }"
                  >
                    {{ `${item.checkInInfo.betweenNowDays} / ${item.checkInInfo.betweenDays}` }}
                  </span>
                  <span v-else class="empty-status">空置</span>
                </div>
              </div>
            </div>
          </el-card>
          <template #dropdown>
            <el-dropdown-menu >
              <el-dropdown-item command="lodgingDetail" v-if="item.checkInInfo.checkInId">入住详情</el-dropdown-item>
<!--              <el-dropdown-item command="permission" >开门权限</el-dropdown-item>-->
<!--              <el-dropdown-item command="showingsPwd" >看房密码</el-dropdown-item>-->
<!--              <el-dropdown-item command="bookingManagement" >预定管理</el-dropdown-item>-->
              <el-dropdown-item command="checkin" v-if="!item.checkInInfo.checkInId">办理入住</el-dropdown-item>
              <el-dropdown-item command="associatedDevice">关联设备</el-dropdown-item>
              <el-dropdown-item command="roomDetail" >房间详情</el-dropdown-item>
<!--              <el-dropdown-item>水电费充值</el-dropdown-item>-->
              <el-dropdown-item command="setDirty" v-if="item.roomDirtyStatus === '0'">置为脏房</el-dropdown-item>
              <el-dropdown-item command="setClean" v-if="item.roomDirtyStatus === '1'">置为净房</el-dropdown-item>
              <el-dropdown-item command="delete" divided>删除</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>
    <el-dialog v-model="addRoomShow" title="添加房间" append-to-body width="500px" :fullscreen="device === 'mobile'" lock-scroll>
      <el-form :model="addRoomForm" label-width="80px">
        <el-row>
          <el-col :span="20">
            <el-form-item prop="room" label="房间号">
              <el-input v-model="addRoomForm.room" placeholder="请输入房间号"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addRoomShow = false">取消</el-button>
          <el-button type="primary" @click="handleAddRoom">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
    <BatchLock v-model:visible="batchLockVisible" @cancel="() => batchLockVisible = false" />
    <UtilityBills v-model:visible="utilityBillsVisible"  @cancel="() => utilityBillsVisible = false" />
    <LodgingDetail 
      :room-info="roomInfo" 
      :check-in-id="roomInfo.checkInInfo?.checkInId" 
      v-model:visible="lodgingDetailVisible" 
      v-if="lodgingDetailVisible" 
      @cancel="handleLodgingDetailCancel"
    />
    <ShowingsPwd
      :visible="showingsPwdVisible"
      @cancel="() => showingsPwdVisible = false"
    />
    <BookingManagement :visible="bookingVisible" @cancel="() => bookingVisible = false" />
    <RoomDetail 
      :room-id="roomInfo.roomId" 
      :building-name="name" 
      :chamber-name="floorName" 
      v-model:visible="roomDetailVisible" 
      v-if="roomDetailVisible"
      @cancel="handleRoomDetailCancel"
      @update="handleRoomUpdate"
    />
    <AssociateDevice 
      :room-id="roomInfo.roomId" 
      :room-name="roomInfo.roomName" 
      v-model:visible="deviceListVisible"
      v-if="deviceListVisible"
      @cancel="handleAssociateDeviceCancel"
      @update="handleDeviceUpdate"
      @associatedRoom="associatedRoomVisible = true"
      @associatedPublic="associatedPublicVisible = true"
    />
    <AssociateRoomDialog :visible="associatedRoomVisible"
                         @openUnbindLock="openUnbindLock"
                         @openUnbindMeter="openUnbindMeter"
                         @cancel="() => associatedRoomVisible = false" />
    <UnbindLockList :room-id="roomInfo.roomId" v-model:visible="unbindLockVisible"
                     v-if="unbindLockVisible"
                     @cancel="() => unbindLockVisible = false"
                    @bind-complete="bindLockComplete"
    />
    <UnbindMeterList :room-id="roomInfo.roomId" v-model:visible="unbindMeterVisible"
                    v-if="unbindMeterVisible"
                    @cancel="() => unbindMeterVisible = false"
                    @bind-complete="bindMeterComplete"
    />
  </div>
</template>
<script setup name='RoomFloor'>
import useAppStore from "@/store/modules/app"
import { ElMessage, ElMessageBox } from 'element-plus'
import BatchLock from './batchLock.vue'
import UtilityBills from './utilityBills.vue'
import LodgingDetail from './lodgingDetail/index.vue'
import ShowingsPwd from './showingsPwd.vue'
import BookingManagement from './bookingManagement/index.vue'
import RoomDetail from './roomDetail/index.vue'
import { useRouter } from "vue-router"
import roomApi from '@/api/room/room'
import buildApi from '@/api/room/building'
import floorApi from '@/api/room/floor'
import {Lock, Odometer, Brush} from "@element-plus/icons-vue";
import AssociateDevice from "./AssociateDevice/index.vue";
import UnbindLockList from "./AssociateDevice/UnbindLockList.vue";
import AssociateRoomDialog from "@/views/room/component/AssociateDevice/AssociateRoomDialog.vue";
import UnbindMeterList from "@/views/room/component/AssociateDevice/UnbindMeterList.vue";
import { deleteRoom, setDirty, setClean } from '@/api/room/room'

const { proxy } = getCurrentInstance()

const router = useRouter()

const emit = defineEmits()
const props = defineProps({
  name: {
    type: String,
    default: ''
  },
  floorName: {
    type: String,
    default: ''
  },
  floorId: {
    type: Number,
    default: null
  },
  roomList: {
    type: Array,
    default: () => []
  },
  info: {
    type: Object,
    default: () => {}
  }
})

const addRoomShow = ref(false)
const batchLockVisible = ref(false)
const utilityBillsVisible = ref(false)
const lodgingDetailVisible = ref(false)
const roomDetailVisible = ref(false)
const deviceListVisible = ref(false)
const associatedRoomVisible = ref(false)
const associatedPublicVisible = ref(false)
const unbindLockVisible = ref(false)
const unbindMeterVisible = ref(false)
const showingsPwdVisible = ref(false)
const bookingVisible = ref(false)
const roomInfo = ref({})
// const roomList = ref([])
const data = reactive({
  addRoomForm: {
    room: undefined
  }
})

const { addRoomForm } = toRefs(data)
const device = computed(() => useAppStore().device)
const title = computed(() => `${props.name} · ${props.floorName}层`)

function handleSelect(index) {
  console.log('select item...', index);
}

function openUnbindLock() {
  unbindLockVisible.value = true
  associatedRoomVisible.value = false
}

function openUnbindMeter() {
  unbindMeterVisible.value = true
  associatedRoomVisible.value = false
}

// 删除整层提示框
function delMessageBox() {
  ElMessageBox.confirm(
    '确认删除整层所有房间？',
    '',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      customStyle: 'width: 320px;'
    }
  )
    .then(() => {
      // 判断该楼层是否还有未退房房间
      // 若有：提示 "楼栋下面还有未退的房间，请先退房"
      floorApi.remove(props.floorId, { buildingId: props.info.buildingId }).then(res => {
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
        emit('addRoom')
      })
    })
    .catch(() => console.log('delete...'))
}

function floorCommand(value) {
  console.log(value);
  switch (value) {
    case 'add':
      addRoomShow.value = true
      break;
    // 删除整层房间
    case 'delFloor':
      delMessageBox()
      break
    case 'batchLock':
      batchLockVisible.value = true
      break
    default:
      break;
  }
}

// 绑定门锁完成
function bindLockComplete() {
  unbindLockVisible.value = false
  associatedRoomVisible.value = false
  emit('refresh')
}

// 绑定门锁完成
function bindMeterComplete() {
  unbindMeterVisible.value = false
  associatedRoomVisible.value = false
  emit('refresh')
}

/* 入住详情关闭 */
function handleLodgingDetailCancel() {
  lodgingDetailVisible.value = false
}

// 点击房间事件
function roomCommand(value, room) {
  console.log(value)
  switch (value) {
    case 'lodgingDetail':
      roomInfo.value = { ...room }
      lodgingDetailVisible.value = true
      break;
    case 'permission':
      router.push({ path: '/room/permission', query: { id: 1 } })
      break;
    case 'showingsPwd':
      showingsPwdVisible.value = true
      break
    case 'bookingManagement':
      bookingVisible.value = true
      break
    case 'delete':
      handleDelete(room)
      break;
    case 'associatedDevice':
      roomInfo.value = { ...room }
      deviceListVisible.value = true
      break
    case 'checkin':
      console.log(room);
      router.push({
        path: '/room/checkin',
        query: { roomId: room.roomId }
      })
      break
    case 'roomDetail':
      roomInfo.value = { ...room }
      roomDetailVisible.value = true
      break
    case 'setDirty':
      handleSetDirty(room)
      break
    case 'setClean':
      handleSetClean(room)
      break
    default:
      break;
  }
}

// 添加房间确认事件
function handleAddRoom() {
  console.log(props.info);
  const params = {
    buildingId: props.info.buildingId,
    floors: [{
      floor: props.info.floorName,
      roomNameList: [addRoomForm.value.room]
    }]
  }
  buildApi.addBuilding(params).then(res => {
    addRoomShow.value = false
    emit('addRoom')
  })
}

/* 删除房间 */
function handleDelete(row) {
  proxy.$modal.confirm('确认要删除该房间吗？').then(() => {
    deleteRoom(row.roomId).then(res => {
      if(res.code === 200) {
        proxy.$modal.msgSuccess('删除成功')
        emit('refresh') // 刷新列表
      }
    })
  }).catch(() => {})
}

/* 置为脏房 */
function handleSetDirty(row) {
  proxy.$modal.confirm('确认要将该房间置为脏房吗？').then(() => {
    setDirty(row.roomId).then(res => {
      if(res.code === 200) {
        proxy.$modal.msgSuccess('操作成功')
        emit('refresh') // 刷新列表
      }
    })
  }).catch(() => {})
}

/* 置为净房 */
function handleSetClean(row) {
  proxy.$modal.confirm('确认要将该房间置为净房吗？').then(() => {
    setClean(row.roomId).then(res => {
      if(res.code === 200) {
        proxy.$modal.msgSuccess('操作成功')
        emit('refresh') // 刷新列表
      }
    })
  }).catch(() => {})
}

/* 判断是否有设备图标 */
function hasDevices(item) {
  return (item.associatedLockList && item.associatedLockList.length !== 0) ||
         (item.associatedMeterList && item.associatedMeterList.length !== 0) ||
         (item.associatedFaceLockList && item.associatedFaceLockList.length !== 0) ||
         item.roomDirtyStatus === '1'
}

/* 房间详情抽屉关闭 */
function handleRoomDetailCancel() {
  roomDetailVisible.value = false
}

/* 关联设备抽屉关闭 */
function handleAssociateDeviceCancel() {
  deviceListVisible.value = false
}

/* 房间信息更新 */
function handleRoomUpdate(updatedRoom) {
  // 更新当前房间信息
  const index = props.roomList.findIndex(room => room.roomId === updatedRoom.roomId)
  if (index !== -1) {
    // 使用解构赋值保持响应性
    props.roomList[index] = { ...props.roomList[index], ...updatedRoom }
  }
}

/* 设备关联更新 */
function handleDeviceUpdate(updatedRoom) {
  // 更新当前房间的设备信息
  const index = props.roomList.findIndex(room => room.roomId === updatedRoom.roomId)
  if (index !== -1) {
    // 只更新设备相关字段
    props.roomList[index].associatedLockList = updatedRoom.associatedLockList
    props.roomList[index].associatedMeterList = updatedRoom.associatedMeterList
  }
}

// function getRoomList() {
//   roomApi.getList({  pageSize: 20, pageNum: 1, type: 1 }).then(res => {
//     roomList.value = res.data
//   })
// }
// getRoomList()
</script>
<style lang="scss" scoped>
.floor-title {
  display: flex;
  align-items: center;
}
.floor-flexrow {
  margin-top: 4px;
  margin-bottom: 14px;
  &-wrap {
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;
  }
  
  .room-item {
    width: 160px;
    height: 100px;
    margin: 6px 4px;
    cursor: pointer;
    transition: all 0.3s;
    
    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
    }

    &.is-checked-in {
      background-color: rgba(64, 158, 255, 0.1);
    }

    :deep(.el-card__body) {
      padding: 12px;
      height: 100%;
    }

    .room-content {
      height: 100%;
      display: flex;
      flex-direction: column;

      .room-header {
        .room-name {
          font-size: 16px;
          font-weight: 500;
        }
      }

      .room-footer {
        margin-top: auto;
        display: flex;
        justify-content: space-between;
        align-items: flex-end;
        
        .room-icons {
          flex: 1;
          display: flex;
          gap: 8px;

          .icon-item {
            .el-icon {
              font-size: 16px;
              color: var(--el-color-primary);
            }

            .dirty-icon {
              color: #e6a23c; // 使用 Element Plus 的警告色
            }
          }
        }

        .room-status {
          text-align: right;
          min-width: fit-content;
          font-size: 12px;
          
          .empty-status {
            color: #e6a23c;
          }
          
          .is-expired {
            color: #f56c6c;
          }
        }
      }
    }
  }
}

.text {
  font-size: 14px;
}

.item {
  position:absolute;
  bottom:0;
  margin-bottom: 18px;
}
</style>